package com.res.share.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.res.share.common.utils.StringUtils;
import com.res.share.common.seo.AISeoArticle;
import com.res.share.common.seo.GooleTranslate;
import com.res.share.common.seo.ImgStypeUtils;
import com.res.share.common.seo.translate.GoogleApi;
import com.res.share.model.ResArt;
import com.res.share.mapper.ResArtMapper;
import com.res.share.model.dto.ArticleModel;
import com.res.share.service.IResArtService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.res.share.service.IResDownService;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 * 资源 服务实现类
 * </p>
 *
 * @author astupidcoder
 * @since 2021-09-13
 */
@Service
public class ResArtServiceImpl extends ServiceImpl<ResArtMapper, ResArt> implements IResArtService {

    @Autowired
    private IResDownService resDownService;

    @Override
    public List<ArticleModel> findArtsList(Integer userId, Integer type) {
        return baseMapper.findArtsList(userId, type);
    }

    @Override
    public IPage<ArticleModel> findHotArticleList(Page<ArticleModel> page, Integer type, Integer userId, Integer resType, List<Integer> cidList) {
        return baseMapper.findHotArticleList(page, type, userId, resType, cidList);
    }

    @Override
    public IPage<ArticleModel> searchArticleList(Page<ArticleModel> page, Integer userId, String keywords) {
        return baseMapper.searchArticleList(page, userId, keywords);
    }

    @Override
    public IPage<ArticleModel> findMyReports(Page<ArticleModel> page, Integer userId) {
        return baseMapper.findMyReports(page, userId);
    }

    @Override
    public ArticleModel findArtDetail(Integer userId, Integer articleId, Integer cId, Integer selectType, Integer artType) {
        return baseMapper.findArticleDetail(userId, articleId, cId, selectType, artType);
    }

    @Override
    public List<ArticleModel> findLikeArticleList() {
        return baseMapper.findLikeArticleList();
    }

    @Override
    public List<ArticleModel> recommendArticleList(List<Integer> cidList, Integer artType) {
        return baseMapper.recommendArticleList(cidList, artType);
    }

    @Override
    public String findArtUploadData(Integer userId, Integer articleId, Integer freeType) {
        String artUploadData = baseMapper.findArtUploadData(articleId);
        resDownService.saveResDown(userId, articleId, freeType);
        return artUploadData;
    }

    @Override
    public void updateArticleLookSee(Integer articleId) {
        baseMapper.updateArticleLookSee(articleId);
    }

    @Override
    public ResArt findArtDataById(Integer articleId) {
        return baseMapper.selectById(articleId);
    }

    @Override
    public IPage<ArticleModel> findTagArticleList(Page<ArticleModel> page, Integer userId, Integer tagId) {
        return baseMapper.findTagArticleList(page, userId, tagId);
    }

    @Override
    public void updateLeanResource() {
        List<Integer> resList = new ArrayList<>();
        Integer totalNums = baseMapper.findLeanResouceCount();
        int pageNo = (int) Math.ceil(1.0 * totalNums / 1000);
        for (int i = 0; i < pageNo; i++) {
            List<ResArt> selectList = baseMapper.findLeanResouceList(((i + 1) - 1) * 1000, 1000);
            if (!CollectionUtils.isEmpty(selectList)) {
                for (ResArt leanResource : selectList) {
                    String resDownload = leanResource.getOpenDetail();
                    if (StringUtils.isEmpty(resDownload) || !resDownload.contains("http") || !resDownload.contains("https")) {
                        resList.add(leanResource.getId());
                        continue;
                    } else {
                        String urlByStr = findUrlByStr(resDownload);
                        if (StringUtils.isNotEmpty(urlByStr)) {
                            boolean checkUrlexit = checkUrlexit(urlByStr);
                            if (!checkUrlexit) {
                                resList.add(leanResource.getId());
                            }
                        } else {
                            resList.add(leanResource.getId());
                            continue;
                        }
                    }
                    String delHTMLTag = null;
                    if (StringUtils.isNotEmpty(leanResource.getContent())) {
                        delHTMLTag = delHTMLTag(leanResource.getContent());
                    }
                    String resName = leanResource.getTitle();
                    resName = resName.replaceAll("\\(\'", "");
                    resName = resName.replaceAll("',\\)", "");
                    baseMapper.updateResArt(delHTMLTag, resName, leanResource.getId());

                }
            }
        }
        if (!CollectionUtils.isEmpty(resList)) {
            System.out.println(resList.toString());
            resList.forEach(integer -> {
                baseMapper.deleteById(integer);
            });
        }
    }

    public static String findUrlByStr(String data) {
//		data = "地球亚洲中国https://www.baidu.com/s?wd=java 厉害厉害！";
        Pattern pattern = Pattern.compile("https?://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]");
        Matcher matcher = pattern.matcher(data);
        if (matcher.find()) {
            return matcher.group();
        }
        return "";
    }

    public static boolean checkUrlexit(String urlData) {
        Boolean isclosed = true;
        BufferedReader br = null;
        InputStreamReader isr = null;
        InputStream is = null;
        try {
            //标志是否失效，默认不失效
            URL url = new URL(urlData);//这里输入你要查询的链接
             is = url.openStream();
            isr = new InputStreamReader(is, "utf-8");
            br = new BufferedReader(isr);
            StringBuilder sb = new StringBuilder();
            String data = br.readLine();
            while (data != null) {
                data = br.readLine();
                sb.append(data);
            }

            String finaldata = sb.toString();
            if (finaldata.contains("分享的文件已经被取消了")
                    || finaldata.contains("此链接分享内容可能因为涉及侵权")
                    || finaldata.contains("你所访问的页面不存在了")) {
                isclosed = false;
            }
        } catch (IOException e) {
            Document doc = null;
            try {
                Connection conn = Jsoup.connect("https://www.baidu.com/");
                conn.method(Connection.Method.GET);
                conn.followRedirects(false);
                Connection.Response response = conn.execute();
                doc = Jsoup.connect(urlData).timeout(5 * 1000)
                        .userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31")
                        .header("Cookie", response.cookies().toString().replaceAll("\\{","").replaceAll("}",""))
                        .get();
                Elements elements = doc.select("div.share-error-left");
                if(elements==null || elements.isEmpty()){
                    isclosed=true;
                }else {
                    isclosed=false;
                }
            } catch (IOException EX) {
                isclosed=false;
            }
        } finally {
            try {
                if(br!=null){
                    br.close();
                }
                if(isr!=null){
                    isr.close();
                }
                if(is!=null){
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return isclosed;
    }

    public static void main(String[] args) {
//            Document doc = null;
//            try {
//                Connection conn = Jsoup.connect("https://www.baidu.com/");
//                conn.method(Connection.Method.GET);
//                conn.followRedirects(false);
//                Connection.Response response = conn.execute();
//                doc = Jsoup.connect("https://pan.baidu.com/share/init?surl=ezZXfcpSu443VmgGmmYZDA").timeout(5 * 1000)
//                        .userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31")
//                        .header("Cookie", response.cookies().toString().replaceAll("\\{","").replaceAll("}",""))
//                        .get();
////                Elements select = doc.select("div.share-error-left");
////                if(select==null || select.isEmpty()){
////                    //存在
////                    System.out.println(true);
////                }else {
////                    System.out.println(false);
////                }
//                //百度网盘 请输入提取码
//                System.out.println(doc.head().select("title").text());
//
////                System.out.println(doc.select("div.share-error-left > div#share_nofound_des").text().contains("此链接分享内容"));
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
        String name = "('[华为] 华为官方讲师轮番上阵-华为HCNP 路由与交换V2.0视频教程 HCNP-R&S-IENP-',)";
        name = name.replaceAll("\\('", "");
        name = name.replaceAll("',\\)", "");
        System.out.println(name);
    }

    public static String delHTMLTag(String htmlStr) {
        htmlStr = htmlStr.replaceAll("<(pre)(.*?)(/>|></pre>|>)", "");
        if (StringUtils.isNotEmpty(htmlStr)) {
            htmlStr = htmlStr.replaceAll("<(img|IMG)(.*?)(/>|></img>|>)", "");
        }
        if (StringUtils.isNotEmpty(htmlStr)) {
            htmlStr = htmlStr.replaceAll("<(divclass)(.*?)(/>|></div>|>)", "");
        }
        if (StringUtils.isNotEmpty(htmlStr)) {
            htmlStr = htmlStr.replaceAll("<a[^>]*>", "");
        }
        if (StringUtils.isNotEmpty(htmlStr)) {
            htmlStr = htmlStr.replaceAll("</a>", "");
        }
        if (StringUtils.isNotEmpty(htmlStr)) {
            htmlStr = htmlStr.replaceAll("<(/div>)", "");
        }
        if (StringUtils.isNotEmpty(htmlStr)) {
            htmlStr = htmlStr.replaceAll("<(/pre>)", "");
        }
        if (StringUtils.isNotEmpty(htmlStr)) {
            htmlStr = htmlStr.trim();
        }
        return htmlStr; //返回文本字符串
    }


    @Override
    public Map<String, String> findArticelAI(String title, String content) {
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("title", title);
        resultMap.put("content", content);
        GooleTranslate gooleTranslate = GooleTranslate.getInstance();
        String s = translateArticleText(title, resultMap, gooleTranslate);
        if (StringUtils.isNotEmpty(s)) {
            resultMap.put("title", s);
        }
        String contentModel = translateArticleText(content, resultMap, gooleTranslate);
        if (StringUtils.isNotEmpty(contentModel)) {
            resultMap.put("content", contentModel);
        }
        return resultMap;
    }

    private String translateArticleText(String title, Map<String, String> resultMap, GooleTranslate gooleTranslate) {
        String text = null;
        Map<String, String> map = gooleTranslate.translateText(title, "zh-cn", "en");
        String status = map.get("status");
        if (StringUtils.isNotEmpty(status) && status.equalsIgnoreCase("0")) {
            Map<String, String> map1 = gooleTranslate.translateText(map.get("text").toString(), "en", "zh-cn");
            String status1 = map1.get("status");
            if (StringUtils.isNotEmpty(status1) && status1.equalsIgnoreCase("0")) {
                text = map1.get("text");
            }
        }
        return text;
    }


    @Override
    public Map<String, String> findArticelAIOne(String title, String content) {
        Map<String, String> resultMap = new HashMap<>();
        GoogleApi googleApi = new GoogleApi();
        String type = "0";
        String translate = googleApi.translatePost(title, "zh_cn", "en");
        if (StringUtils.isNotEmpty(translate)) {
            String translateONe = googleApi.translatePost(translate, "en", "zh_cn");
            if (StringUtils.isNotEmpty(translateONe)) {
                title = translateONe;
            }
        }
        //文本处理
        //每一个图片对象的key--value
        Map<String, String> imgMap = new HashMap<>();
        String contentModel = ImgStypeUtils.replaceArticleImg(imgMap, content);
        //去除html标签
        String removeHtmlTag = ImgStypeUtils.removeHtmlTag(contentModel);
        StringBuilder stringBuilder = new StringBuilder();
        if (StringUtils.isNotEmpty(removeHtmlTag)) {
            String translatecontent = googleApi.translatePost(removeHtmlTag, "zh_cn", "en");
            if (StringUtils.isNotEmpty(translatecontent)) {
                String translateONecontent = googleApi.translatePost(translatecontent, "en", "zh_cn");
                if (StringUtils.isNotEmpty(translateONecontent)) {
                    //文章切割 添加img标签 添加p标签
                    List<String> sliceArticleList = AISeoArticle.sliceArticle(translateONecontent);
                    if (!CollectionUtils.isEmpty(sliceArticleList)) {
                        if (sliceArticleList.size() == 1) {
                            String info = sliceArticleList.get(0);
                            //图片替换
                            if (imgMap != null && StringUtils.isNotEmpty(info)) {
                                imgMap.forEach((key, value) -> {
                                    info.replace(key, value);
                                });
                            }
                            stringBuilder.append("<p>" + info + "</p>");
                        } else {
                            sliceArticleList.forEach(s -> {
                                if (imgMap != null && StringUtils.isNotEmpty(s)) {
                                    imgMap.forEach((key, value) -> {
                                        s.replace(key, value);
                                    });
                                }
                                stringBuilder.append("<p>" + s + "</p>");
                            });
                        }
                    }
                }
            }
        } else {
            type = "1";//原来文章 未翻译
        }
        if (stringBuilder != null) {
            content = stringBuilder.toString();
        }
        resultMap.put("type", type);
        resultMap.put("title", title);
        resultMap.put("content", content);
        return resultMap;
    }

    @Override
    public IPage<ArticleModel> findUserSHopResList(Page<ArticleModel> page, Integer userId, Integer beLongUserId) {
        return baseMapper.findUserSHopResList(page,userId,beLongUserId);
    }

}
